package com.andy.android.serialporttest

import android.annotation.SuppressLint
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andy.android.serialporttest.databinding.ActivityMainBinding
import com.andy.android.usbmanager.USBMan
import com.andy.android.usbmanager.USBReceiver
import com.andy.android.usbmanager.USBReceiver.ACTION_USB_PERMISSION
import com.andy.android.usbmanager.data.GNRMC
import com.andy.android.usbmanager.data.GNRMCObservable
import com.andy.android.usbmanager.data.GNRMCObserver
import com.andy.android.usbmanager.log.LogCall
import com.andy.android.usbmanager.log.LogCallback

class MainActivity : AppCompatActivity(), LogCallback, GNRMCObserver {


    var content = ""

    val receiver = USBReceiver()
    lateinit var binding: ActivityMainBinding
    private val list = mutableListOf<String>()
    val adapter = MyAdapter(list)




    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
        LogCall.unregisterCallback(this)
        GNRMCObservable.INSTANCE.unregister(this)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {

        Log.init(this)

        // 注册系统USB通知广播
        val filter =  IntentFilter(ACTION_USB_PERMISSION)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        registerReceiver(receiver,filter)
        // 注册日志打印
        LogCall.registerCallback(this)
        // 注册RMC数据读取
        GNRMCObservable.INSTANCE.register(this)



        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)

        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = adapter



        binding.init.setOnClickListener {
            USBMan.INSTANCE.initUsbDevice(this)
        }

        binding.btnClean.setOnClickListener {
            list.clear()
            adapter.notifyDataSetChanged()
        }

    }

    /**
     * 日志回调
     */
    override fun onLog(content: String?) {
//        content?.let {
//            list.add(it)
//            adapter.notifyItemInserted(list.size)
//        }

    }

    /**
     * 数据回调
     */
    override fun onGNRMCChanged(gnrmc: GNRMC?) {
        gnrmc?.let {
            list.add(it.toString())
            adapter.notifyItemInserted(list.size)
        }
    }
}